package com.tvunetworks.center.user.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.tvunetworks.center.common.constant.LocalConstant;
import com.tvunetworks.center.common.exception.ServerException;
import com.tvunetworks.center.common.model.LoginUser;
import com.tvunetworks.center.common.util.Result;
import com.tvunetworks.center.common.util.ResultUtil;
import com.tvunetworks.center.user.mapper.RoleManagementMapper;
import com.tvunetworks.center.user.model.*;
import com.tvunetworks.center.user.model.param.AddRoleManagementParam;
import com.tvunetworks.center.user.model.param.PageRoleParam;
import com.tvunetworks.center.user.model.param.SearchRoleUserParam;
import com.tvunetworks.center.user.model.param.UpdateRoleManagementParam;
import com.tvunetworks.center.user.model.result.ResultConstant;
import com.tvunetworks.center.user.model.vo.*;
import com.tvunetworks.center.user.service.*;
import com.tvunetworks.center.user.service.feign.DeviceFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Etan Yang
 * @data: 2021/4/7 15:19
 * @program: tvucc-aggregator
 * @description:
 */

@Service
@Slf4j
public class RoleManagementServiceImpl extends BaseService<RoleManagement> implements RoleManagementService {
    @Autowired
    private RoleManagementMapper roleManagementMapper;
    @Autowired
    private RoleDeviceService roleDeviceService;
    @Autowired
    private RoleFeatureService roleFeatureService;
    @Autowired
    private UserFeatureService userFeatureService;
    @Autowired
    private UserDeviceService userDeviceService;
    @Autowired
    private UserService userService;
    @Autowired
    private RoleUserService roleUserService;
    @Autowired
    private UserDeviceServiceImpl userDeviceServiceImpl;
    @Autowired
    private DeviceFeignService deviceFeignService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> addRoleManagement(LoginUser loginUser, AddRoleManagementParam param) {
        if (!LocalConstant.UserRole.ADMIN.equalsIgnoreCase(loginUser.getRole())) {
            return ResultConstant.RoleManagement.ADMIN_PERMISSION;
        }
        String userId = loginUser.getId();
        User user = userService.getById(userId);
        if (user == null) {
            return ResultConstant.RoleManagement.USER_NOT_EXIST;
        }
        //1.校验
        String roleName = param.getRoleName();
        //1.1.校验该用户下是否存在该roleName，若存在则直接报错
        RoleManagement roleManagement = roleManagementMapper.getRoleManagementByRoleNameAndUserId(roleName, userId);
        if (roleManagement != null) {
            return ResultConstant.RoleManagement.ROLE_NAME_IS_EXIST;
        }
        Set<String> receiverIdSet = null;
        Set<String> featureSet = null;
        if (StringUtils.isNotEmpty(param.getFeatureIds())) {
            featureSet = new HashSet<>(Arrays.asList(param.getFeatureIds().split(",")));
        }
        if (StringUtils.isNotEmpty(param.getReceiverIds())) {
            receiverIdSet = new HashSet<>(Arrays.asList(param.getReceiverIds().split(",")));
        }
        String result = this.checkDeviceAndFeatureIsLegal(userId, receiverIdSet, featureSet);
        if (StringUtils.isNotEmpty(result)) {
            return ResultUtil.error("81003304", result);
        }
        //2.添加到roleManagement表中
        roleManagement =new RoleManagement()
                .setUserId(userId)
                .setRoleName(roleName);
        super.insert(roleManagement);
        //3.添加到t_role_device表中
        String roleId = roleManagement.getId();
        if (CollectionUtils.isNotEmpty(receiverIdSet)) {
            roleDeviceService.batchInsert(roleId, receiverIdSet);
        }
        //4.添加到t_role_feature表中
        if (CollectionUtils.isNotEmpty(featureSet)) {
            List<RoleFeature> features = new ArrayList<>();
            featureSet.forEach(s->{
                RoleFeature roleFeature = new RoleFeature()
                        .setFeatureId(s)
                        .setRoleId(roleId);
                features.add(roleFeature);
            });
            roleFeatureService.batchAddRoleFeature(features);
        }
        return ResultUtil.success();
    }

    @Override
    public Result<Object> pageRole(String userId, PageRoleParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        return ResultUtil.success(new PageInfo<>(roleManagementMapper.pageRole(userId, param)));
    }

    @Override
    public Result<Object> updateRole(LoginUser loginUser, UpdateRoleManagementParam param) {
        //1.校验
        if (!LocalConstant.UserRole.ADMIN.equalsIgnoreCase(loginUser.getRole())) {
            return ResultConstant.RoleManagement.ADMIN_PERMISSION;
        }
        String userId = loginUser.getId();
        User user = userService.getById(userId);
        if (user == null) {
            return ResultConstant.RoleManagement.USER_NOT_EXIST;
        }
        String roleName = param.getRoleName();
        String roleId = param.getRoleId();
        RoleManagement roleManagement = super.selectExistByPrimaryKey(roleId);
        //1.1.校验该role是否存在
        if (roleManagement == null ||!StringUtils.equals(userId, roleManagement.getUserId())) {
            return ResultConstant.RoleManagement.ROLE_NOT_EXIST;
        }
        //1.2.校验名字是否重复
        if (!StringUtils.equals(roleName, roleManagement.getRoleName())) {
            RoleManagement role = roleManagementMapper.getRoleManagementByRoleNameAndUserId(roleName, userId);
            if (role != null && !StringUtils.equals(role.getId(), roleId)) {
                return ResultConstant.RoleManagement.ROLE_NAME_IS_EXIST;
            }
        }
        //1.3.校验device和feature是否存在
        Set<String> receiverIdSet = null;
        Set<String> featureSet = null;
        if (StringUtils.isNotEmpty(param.getAddFeatureIds())) {
            featureSet = new HashSet<>(Arrays.asList(param.getAddFeatureIds().split(",")));
        }
        if (StringUtils.isNotEmpty(param.getAddReceiverIds())) {
            receiverIdSet = new HashSet<>(Arrays.asList(param.getAddReceiverIds().split(",")));
        }
        String result = this.checkDeviceAndFeatureIsLegal(userId, receiverIdSet, featureSet);
        if (StringUtils.isNotEmpty(result)) {
            return ResultUtil.error("81003304", result);
        }
        //2.修改role
        if (!StringUtils.equals(roleName, roleManagement.getRoleName())) {
            roleManagement.setRoleName(roleName);
            super.updateSelective(roleManagement);
        }
        //3.添加/删除roleFeature
        //3.1.在role_feature表中删除feature
        if (StringUtils.isNotEmpty(param.getDeleteFeatureIds())) {
            roleFeatureService.batchDeleteByRoleIdAndFeatureIds(roleId, Arrays.asList(param.getDeleteFeatureIds().split(",")));
        }
        //3.2.在role_feature表中添加feature
        if (CollectionUtils.isNotEmpty(featureSet)) {
            List<RoleFeature> features = new ArrayList<>();
            featureSet.forEach(s->{
                RoleFeature rolePermission = new RoleFeature();
                rolePermission.setFeatureId(s)
                        .setRoleId(param.getRoleId());
                features.add(rolePermission);
            });
            roleFeatureService.batchAddRoleFeature(features);
        }
        //3.3.在user_feature表中添加或删除feature
        List<RoleUser> roleUsers = roleUserService.getByRoleId(roleId);
        if (StringUtils.isNotEmpty(param.getDeleteFeatureIds()) || StringUtils.isNotEmpty(param.getAddFeatureIds())) {
            if (CollectionUtils.isNotEmpty(roleUsers)) {
                roleUsers.forEach(s->{
                    User byId = userService.getById(s.getUserId());
                    if (byId == null) {
                        log.error("roleManagementService>>>updateRole>>> user account is not exist,userId:[{}],parentUserId:[{}]"
                                , s.getUserId(), userId);
                        return;
                    }
                    List<String> addFeatureIds = new ArrayList<>(Arrays.asList(param.getAddFeatureIds().split(",")));
                    List<String> deleteFeatureIds = new ArrayList<>(Arrays.asList(param.getDeleteFeatureIds().split(",")));
                    userFeatureService.addAndRemoveFeatureListByUserId(s.getUserId(), byId.getRole(), userId, addFeatureIds, deleteFeatureIds);
                });
            }
        }
        //4.添加/删除roleDevice
        //4.1.删除t_role_device表中的数据
        if (StringUtils.isNotEmpty(param.getDeleteReceiverIds())) {
            roleDeviceService.batchDeleteByRoleIdAndPeerIds(roleId, Arrays.asList(param.getDeleteReceiverIds().split(",")));
        }
        //4.2.添加到t_role_device表中
        if (CollectionUtils.isNotEmpty(receiverIdSet)) {
            roleDeviceService.batchInsert(param.getRoleId(), receiverIdSet);
        }
        //4.3.添加/删除t_user_device表中数据
        if (CollectionUtils.isNotEmpty(roleUsers)) {
            List<String> userIds = roleUsers.stream().map(RoleUser::getUserId).collect(Collectors.toList());
            if (StringUtils.isNotEmpty(param.getDeleteReceiverIds())) {
                ArrayList<String> removePeerIds = new ArrayList<>(Arrays.asList(param.getDeleteReceiverIds().split(",")));
                userDeviceService.unbindUserReceiverCenter(loginUser.getId(), removePeerIds, userIds);
            }
            if (StringUtils.isNotEmpty(param.getAddReceiverIds())) {
                ArrayList<String> addPeerIds = new ArrayList<>(Arrays.asList(param.getAddReceiverIds().split(",")));
                userDeviceService.bindUserReceiverCenter(loginUser.getId(), addPeerIds, userIds);
            }
        }
        return ResultUtil.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Object> deleteRole(LoginUser loginUser, String roleId) {
        //1.校验
        if (!LocalConstant.UserRole.ADMIN.equalsIgnoreCase(loginUser.getRole())) {
            return ResultConstant.RoleManagement.ADMIN_PERMISSION;
        }
        String userId = loginUser.getId();
        RoleManagement roleManagement = super.selectExistByPrimaryKey(roleId);
        //1.1.校验该role是否存在
        if (roleManagement == null ||!StringUtils.equals(userId, roleManagement.getUserId())) {
            return ResultConstant.RoleManagement.ROLE_NOT_EXIST;
        }
        //2.删除t_role中的数据
        super.deleteLogicById(roleId);
        //3.删除t_role_device
        roleDeviceService.deleteByRoleId(roleId);
        //4.删除t_role_feature
        roleFeatureService.deleteByRoleId(roleId);
        //5.删除role_user
        roleUserService.deleteByRoleId(roleId);
        return ResultUtil.success();
    }

    @Override
    public Result<Object> pageRoleName(String userId, PageRoleParam param) {
        PageHelper.startPage(param.getPageNum(), param.getPageSize());
        return ResultUtil.success(new PageInfo<>(roleManagementMapper.pageRoleName(userId, param)));
    }

    @Override
    public RoleVo getRoleByRoleId(String roleId, String userId) {
        RoleManagement roleManagement = roleManagementMapper.getRoleManagementByRoleIdAndUserId(roleId, userId);
        if (roleManagement == null) {
            return null;
        }
        RoleVo roleVo = new RoleVo();
        roleVo.setRoleName(roleManagement.getRoleName())
                .setRoleId(roleId);
        List<RoleFeature> roleFeatures = roleFeatureService.getByRoleId(roleId);
        if (CollectionUtils.isNotEmpty(roleFeatures)) {
            roleVo.setFeatureIds(roleFeatures.stream().map(RoleFeature::getFeatureId).collect(Collectors.toList()));
        }
        List<String> peerIds = roleDeviceService.getPeerIdsByRoleId(roleId);
        if (CollectionUtils.isNotEmpty(peerIds)) {
            Set<String> set = new HashSet<>();
            //获取到peerId,如果设备是R,需查询出和该R配对的全部其他设备.
            peerIds.forEach(s->{
                if (StringUtils.equals(deviceFeignService.getCurrentDevice(s).getType(),"R")){
                    set.add(s);
                }
            });
            if (CollectionUtils.isNotEmpty(set)){
                Set<String> tids = userDeviceServiceImpl.listRsPairTids(set);
                Set<String> xids = userDeviceServiceImpl.listRsPairedXids(set);
                for (String tid : tids) {
                    peerIds.add(tid);
                }
                for (String xid : xids) {
                    peerIds.add(xid);
                }
            }

            roleVo.setPeerIds(peerIds);
        }
      /*  List<RoleUser> users = roleUserService.getByRoleId(roleId);
        if (CollectionUtils.isNotEmpty(users)) {
            roleVo.setUserIds(users.stream().map(RoleUser::getUserId).collect(Collectors.toList()));
        }*/
        return roleVo;
    }

    @Override
    public RoleManagement getByRoleId(String roleId) {
        return super.selectExistByPrimaryKey(roleId);
    }

    @Override
    public void deleteByUserId(String userId) {
        List<RoleManagement> roleManagements = roleManagementMapper.getRoleManagementByUserId(userId);
        if (CollectionUtils.isNotEmpty(roleManagements)) {
            roleManagements.forEach(s->{
                String roleId = s.getId();
                roleDeviceService.deleteByRoleId(roleId);
                roleFeatureService.deleteByRoleId(roleId);
                roleUserService.deleteByRoleId(roleId);
                super.deleteLogicById(roleId);
            });
        }

    }

    @Override
    public void deleteByUserIdAndPeerId(String userId, List<String> peerIds) {
        if (CollectionUtils.isNotEmpty(peerIds)){
         roleManagementMapper.deleteByUserIdAndPeerId(userId,peerIds);
        }
    }

    @Override
    public Map<String, Map<RoleManagement, List<String>>> listDataFromManageRole() {
        long startTime = System.currentTimeMillis();
        Map<String, Map<RoleManagement, List<String>>> deleteResultMap = new HashMap<>();
        //1.先查询出有多少个用户创建过 role_manage  查出userId (多少用户产生脏数据)
        List<String> userIdList = this.getUserByRoleManage();
        log.error("listDataFromManageRole>>>>>>>>AdminUserId is userIdList:[{}]", userIdList);
        //2.分批查询
        if (CollectionUtils.isNotEmpty(userIdList)) {
            int pageSize = 50;
            int page = userIdList.size() / pageSize + (userIdList.size() % pageSize == 0 ? 0 : 1);
            for (int pageNum = 0; pageNum < page; pageNum++) {
                //2.1.分批
                int startIndex = pageNum * pageSize;
                List<String> needUserIds;
                if (startIndex == 0) {
                    needUserIds = userIdList.stream().limit(pageSize).collect(Collectors.toList());
                } else {
                    needUserIds = userIdList.stream().skip(startIndex).limit(pageSize).collect(Collectors.toList());
                }
                //2.2.查询
                needUserIds.forEach(userId -> {
                    //1)查询该用户下所有的R
                    List<String> userDeviceList = userDeviceService.listUserDevice(userId, null, "R");
                    List<String> adminDeviceList = userDeviceList.stream().map(String::toLowerCase).collect(Collectors.toList());
                    log.error("listDataFromManageRole11111>>>>> adminUserDevice  userId:[{}],userDeviceList:[{}]", userId, userDeviceList);
                    //2)查询user下所有的role对应的设备
                    List<RoleManagement> roleManagements = roleManagementMapper.getRoleManagementByUserId(userId);
                    if (CollectionUtils.isNotEmpty(roleManagements)) {
                        roleManagements.forEach(roleManagement -> {
                            //查询该role下有多少设备
                            List<String> peerIdsByRoleId = roleDeviceService.getPeerIdsByRoleId(roleManagement.getId());
                            log.error("listDataFromManageRole22222>>>>>>>>userRoleDevice,roleInfo:[{}],devices:[{}]", roleManagement, peerIdsByRoleId);
                            if (CollectionUtils.isNotEmpty(peerIdsByRoleId)) {
                                peerIdsByRoleId = peerIdsByRoleId.stream().map(String::toLowerCase).collect(Collectors.toList());
                                peerIdsByRoleId.removeAll(adminDeviceList);
                                log.error("listDataFromManageRole3333>>>>>>>>>>> roleInfo:[{}],deletePeerIds:[{}]", roleManagement, peerIdsByRoleId);
                                if (CollectionUtils.isNotEmpty(peerIdsByRoleId)) {
                                    Map<RoleManagement, List<String>> deletePeerIdMap = new HashMap<>();
                                    deletePeerIdMap.put(roleManagement, peerIdsByRoleId);
                                    deleteResultMap.put(userId, deletePeerIdMap);
                                }
                            }
                        });
                    }
                });
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.error("listDataFromManageRole888>>>>>>>sleep exception,",e);
                }
            }
        }
        long spendTime = System.currentTimeMillis() - startTime;
        log.error("listDataFromManageRole>>>>>>>>>>>>Result,,spendTime:[{}],deleteResultMap:[{}] ", spendTime, deleteResultMap);
        return deleteResultMap;
    }

    @Override
    public List<RoleDevice> deleteRoleDevice(String userId) {
        User user = userService.getById(userId);
        if (user == null) {
            throw new ServerException(ResultConstant.User.USER_NOT_EXIST);
        }
        List<RoleDevice> result = new ArrayList<>();
        log.error("deleteRoleDevice>>>>>>>>>delete roleDevice by userId:[{}],user:[{}]", userId, user);
        Map<String, Map<RoleManagement, List<String>>> stringMapMap = this.listDataFromManageRole();
        if (stringMapMap != null && stringMapMap.size() > 0) {
            for (Map.Entry<String, Map<RoleManagement, List<String>>> stringMapEntry : stringMapMap.entrySet()) {
                log.error("deleteRoleDevice1111>>>>>>>>beforeDelete, userId:[{}],roleManagementMap:[{}]", stringMapEntry.getKey(), stringMapEntry.getValue());
                for (Map.Entry<RoleManagement, List<String>> roleManagementListEntry : stringMapEntry.getValue().entrySet()) {
                    log.error("deleteRoleDevice22222>>>>>>>>beforeDelete, userId:[{}],roleManagementMap:[{}]", roleManagementListEntry.getKey(), roleManagementListEntry.getValue());
                    List<RoleDevice> roleDevices = roleDeviceService.listRoleDeviceByRoleIdAndPeerIds(roleManagementListEntry.getKey().getId(), roleManagementListEntry.getValue());
                    if (CollectionUtils.isNotEmpty(roleDevices)) {
                        List<String> roleDeviceIds = roleDevices.stream().map(RoleDevice::getId).collect(Collectors.toList());
                        log.error("deleteRoleDevice333333>>>>>>>>roleDeviceIdList:[{}] ", roleDeviceIds);
                        log.error("deleteRoleDevice333333>>>>>>>>roleDevices:[{}] ", roleDevices);
                        roleDeviceService.batchDeleteByIds(roleDeviceIds);
                        result.addAll(roleDevices);
                    }
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    log.error("deleteRoleDevice7777>>>>sleep exception",e);
                }

            }
        }
        log.error("deleteRoleDevice88888>>>>>>>>roleDevices:[{}] ", result);
        return result;
    }

    @Override
    public Result<Object> getRoleMessage(LoginUser loginUser, SearchRoleUserParam param) {
        String roleId = param.getRoleId();
        String condition = param.getCondition();
        if (!LocalConstant.UserRole.ADMIN.equalsIgnoreCase(loginUser.getRole())) {
            return ResultConstant.RoleManagement.ADMIN_PERMISSION;
        }
        UpdateRoleUserVo updateRoleUserVo = new UpdateRoleUserVo();
        if (StringUtils.isEmpty(roleId)) {
            //添加
            Result<UpdateUserFeatureVo> result = userFeatureService.listFeatureForCreate(loginUser, LocalConstant.UserRole.USER);
            if (!result.assertSuccess()) {
                return ResultUtil.error(result.getErrorCode(), result.getErrorInfo());
            }
            //添加feature
            UpdateUserFeatureVo updateUserFeatureVo = result.getResult();
            if (updateUserFeatureVo != null) {
                updateRoleUserVo.setAccessPage(updateUserFeatureVo.getAccessPages());
                updateRoleUserVo.setAdminAutoOwnFeatures(updateUserFeatureVo.getAdminAutoOwnFeatures());
                updateRoleUserVo.setOtherFeatures(updateUserFeatureVo.getOtherFeatures());
            }
            //添加device
            List<SearchUserDeviceVo> searchUserDeviceVos = userDeviceService.getReceiverListByUserId(loginUser.getId(), condition);
            if (CollectionUtils.isNotEmpty(searchUserDeviceVos)) {
                updateRoleUserVo.setDevices(searchUserDeviceVos);
            }
        }else {
            //修改
            RoleManagement roleManagement = super.selectExistByPrimaryKey(roleId);
            if (roleManagement == null) {
                return ResultConstant.RoleManagement.ROLE_NOT_EXIST;
            }
            // 查询出所有可勾选的框
            updateRoleUserVo.setRoleId(roleId);
            updateRoleUserVo.setRoleName(roleManagement.getRoleName());
            Result<UpdateUserFeatureVo> result = userFeatureService.listFeatureForCreate(loginUser, LocalConstant.UserRole.USER);
            if (!result.assertSuccess()) {
                return ResultUtil.error(result.getErrorCode(), result.getErrorInfo());
            }
            UpdateUserFeatureVo updateUserFeatureVo = result.getResult();
            this.setRoleUserVoEnableField(roleId, updateUserFeatureVo, updateRoleUserVo);
            //查询该用户下所有的device
            List<SearchUserDeviceVo> searchUserDeviceVos = userDeviceService.getReceiverListByUserId(loginUser.getId(), condition);
            if (CollectionUtils.isNotEmpty(searchUserDeviceVos)) {
                List<String> peerIds = roleDeviceService.getPeerIdsByRoleId(roleId);
                if (CollectionUtils.isNotEmpty(peerIds)) {
                    searchUserDeviceVos.forEach(s -> s.setEnableRelation(peerIds.contains(s.getPeerId()) ? 1 : 0));
                }
            }
            updateRoleUserVo.setDevices(searchUserDeviceVos);
        }

        return ResultUtil.success(updateRoleUserVo);
    }

    @Override
    public List<SearchUserDeviceVo> getReceiverList(String userId, SearchRoleUserParam param) {
        List<SearchUserDeviceVo> searchUserDeviceVos = userDeviceService.getReceiverListByUserId(userId, param.getCondition());
        if (StringUtils.isEmpty(param.getRoleId())) {
            return searchUserDeviceVos;
        }
        if (CollectionUtils.isNotEmpty(searchUserDeviceVos)) {
            List<String> peerIds = roleDeviceService.getPeerIdsByRoleId(param.getRoleId());
            if (CollectionUtils.isNotEmpty(peerIds)) {
                searchUserDeviceVos = searchUserDeviceVos.stream().filter(s -> !peerIds.contains(s.getPeerId())).collect(Collectors.toList());
            }
        }
        return searchUserDeviceVos;
    }

    /**
     * 根据roleId查询对应的ro为UserFeatureVo列表设置enable属性
     *
     * @param roleId
     */
    private void setRoleUserVoEnableField(String roleId, UpdateUserFeatureVo updateUserFeatureVo, UpdateRoleUserVo updateRoleUserVo) {
        Set<String> enableFeatureIds = new HashSet<>();
        // 查询该role拥有的featureId集合
        List<RoleFeature> roleFeatures = roleFeatureService.getByRoleId(roleId);
        List<String> roleFeatureIds = roleFeatures.stream().map(RoleFeature::getFeatureId).collect(Collectors.toList());
        if (CollectionUtils.isNotEmpty(roleFeatureIds)) {
            enableFeatureIds.addAll(roleFeatureIds);
        }
        //更新adminAutoOwnFeatures是否应用
        List<UserFeatureVo> adminAutoOwnFeatures = updateUserFeatureVo.getAdminAutoOwnFeatures();
        if (CollectionUtils.isNotEmpty(adminAutoOwnFeatures)) {
            adminAutoOwnFeatures.forEach(s -> s.setEnable(enableFeatureIds.contains(s.getFeatureId()) ? 1 : 0));
        }
        updateRoleUserVo.setAdminAutoOwnFeatures(adminAutoOwnFeatures);
        List<UserFeatureVo> accessPageFeatures = updateUserFeatureVo.getAccessPages();
        if (CollectionUtils.isNotEmpty(accessPageFeatures)) {
            accessPageFeatures.forEach(s -> s.setEnable(enableFeatureIds.contains(s.getFeatureId()) ? 1 : 0));
        }
        updateRoleUserVo.setAccessPage(accessPageFeatures);
        List<UserFeatureVo> otherOwnFeatures = updateUserFeatureVo.getOtherFeatures();
        if (CollectionUtils.isNotEmpty(otherOwnFeatures)) {
            otherOwnFeatures.forEach(s -> s.setEnable(enableFeatureIds.contains(s.getFeatureId()) ? 1 : 0));
        }
        updateRoleUserVo.setOtherFeatures(otherOwnFeatures);
    }

    /**
     * 校验userId下device和feature是否全部存在
     * @param userId
     * @param receiverIds
     * @param featureIds
     * @return
     */
    private String checkDeviceAndFeatureIsLegal(String userId, Set<String> receiverIds, Set<String> featureIds) {
        //1.校验device
        if (CollectionUtils.isNotEmpty(receiverIds)) {
            List<String> existPeerIds = userDeviceService.listUserCacheRids(userId);
            Set<String> peerIdSet = new HashSet<>(receiverIds);
            if (CollectionUtils.isNotEmpty(existPeerIds)) {
                peerIdSet.removeAll(existPeerIds);
            }
            if (CollectionUtils.isNotEmpty(peerIdSet)) {
                StringBuilder sb = new StringBuilder();
                peerIdSet.forEach(s -> sb.append(s).append(","));
                sb.append("This device dose not exist or are not receiver or dose not belong to this account!");
                return sb.toString();
            }
        }
        //2.校验feature是否存在且是否属于这个父账号
        if (CollectionUtils.isNotEmpty(featureIds)) {
            StringBuilder sb = new StringBuilder();
            featureIds.forEach(s->{
                if (!userFeatureService.isUserExistFeature(userId, s)) {
                    sb.append(s).append(",");
                }
            });
            if (StringUtils.isNotEmpty(sb.toString())) {
                sb.append("This featureId dest not exist or not under user!");
                return sb.toString();
            }

        }
        return null;
    }

    /**
     *  获取创建过role_manage的所有用户
     * @return userid集合
     */
    public List<String > getUserByRoleManage() {

        List<String> userId = roleManagementMapper.getUserId();
        return userId;
    }
}
